const app = getApp()
const util = require('../../utils/util.js')

Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    theme: app.globalData.theme, //全局颜色变量
    config: app.globalData.config,
    loadmore: false,
    orderList: [],
    swiperData: [],
    noticeData: [],
    providerInfo: {
      id: null,
      // 工作状态 0休息中，1接单中
      takingStatus: '0'
    },
    orderCountAll: {},
    addressComponent: {
      city: null,
      address: null,
      longitude: null,
      latitude: null
    },
    switchChecked: false
  },
  onLoad(options) {
    // 保存别人分享来的 userCode
    //util.saveSharerUserCode(options);
    app.initPage()
      .then(res => {
        // this.swiperGet()
        this.noticeGet()
        this.loadProviderInfo();
      })
  },
  onShow() {
    if (this.data.addressComponent.longitude) {
      this.refresh()
      this.orderCountAll()
    }
  },
  // 获取当前师傅信息
  loadProviderInfo() {
    const that = this
    app.api.checkUser().then(res1 => {
      if (res1.data) {
        app.api.providerInfoGet().then(res => {
          let data = res.data || {}
          if (data.id) {
            that.setData({
              providerInfo: data,
              switchChecked: data.takingStatus == '1'
            })
            that.orderCountAll()
            that.loadLocation()
          } else {
            // 跳转申请页面
            wx.navigateTo({
              url: "/pages/apply/index"
            })
          }
        })
      }
    })
  },
  // 查询订单数
  orderCountAll() {
    app.api.providerOrderCountAll()
      .then(res => {
        this.setData({
          orderCountAll: res.data
        })
      })
  },
  // 获取经纬度
  loadLocation: function () {
    const _this = this;
    app.checkLocation().then(function (res) {
      app.getCurrentLocation().then(function (res) {
        _this.setData({
          "addressComponent.latitude": res.latitude,
          "addressComponent.longitude": res.longitude
        });
        app.globalData.addressComponent = _this.data.addressComponent
        // 更新全局位置信息
        // 加载订单列表
        _this.loadOrderList()
        // 更新师傅位置信息
        app.api.updateProviderInfo({
          longitude: res.longitude,
          latitude: res.latitude
        }).then(res => {})
      }).catch(function (error) {
        console.log(error);
        _this.loading = false;
        wx.showToast({
          title: "获取位置信息失败，请检查是否打开位置权限",
          icon: 'none',
          duration: 2000
        });
      });
    });
  },
  onShareAppMessage: function () {
    let title = '这里修车师傅端'
    var userInfo = wx.getStorageSync('user_info');
    var userCode = userInfo ? '&sharer_user_code=' + userInfo.userCode : '';
    let path = 'pages/home/index?0' + userCode
    return {
      title: title,
      path: path,
      success: function (res) {
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(res.errMsg)
        }
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  //获取轮播图
  swiperGet() {
    app.api.noticeGet({
        type: '1',
        enable: '1'
      })
      .then(res => {
        let notice = res.data
        if (notice) {
          this.setData({
            swiperData: notice.listNoticeItem
          })
        }
      })
  },
  //获取广告通知
  noticeGet() {
    app.api.noticeGet({
        type: '2',
        enable: '1'
      })
      .then(res => {
        let notice = res.data
        if (notice) {
          this.setData({
            noticeData: notice.listNoticeItem
          })
        }
      })
  },
  // 加载订单列表
  loadOrderList() {
    if (this.data.addressComponent.longitude) {
      app.api.providerOrderList({
        longitude: this.data.addressComponent.longitude,
        latitude: this.data.addressComponent.latitude
      }).then(res => {
        let orderList = res.data || []
        this.setData({
          orderList: orderList
        })
      })
    }
  },
  // 接单
  acceptOrder(e) {
    let that = this;
    wx.showModal({
      content: '是否确认接单？',
      cancelText: '我再想想',
      confirmColor: '#ff0000',
      success(res) {
        if (res.confirm) {
          app.api.providerAcceptOrder({
            id: e.currentTarget.dataset.id
          }).then(res => {
            wx.showToast({
              title: '接单成功',
              icon: 'success',
              duration: 2000
            })
            setTimeout(function () {
              wx.navigateTo({
                url: "/pages/order/order-detail/index?id=" + e.currentTarget.dataset.id
              })
            }, 500)
          })
        }
      }
    })
  },
  refresh() {
    this.setData({
      orderList: [],
    })
    if (this.checkProvider()) {
      this.loadOrderList()
    }
  },
  onPullDownRefresh() {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading()
    this.refresh()
    // 隐藏导航栏加载框
    wx.hideNavigationBarLoading()
    // 停止下拉动作
    wx.stopPullDownRefresh()
  },
  onReachBottom() {},
  jumpPage(e) {
    let page = e.currentTarget.dataset.page
    if (page) {
      wx.navigateTo({
        url: page
      })
    }
  },
  // 跳转地图导航
  jumpMap(e) {
    let index = e.currentTarget.dataset.index
    let order = this.data.orderList[index]
    wx.openLocation({
      latitude: Number(order.latitude),
      longitude: Number(order.longitude),
      scale: 15,
      address: order.userAddress
    })
  },
  onChange(event) {
    const detail = event.detail;
    const that = this;
    if (that.checkProvider()) {
      wx.showModal({
        content: '是否确认' + (detail.value ? '开始接单' : '休息') + '？',
        cancelText: '我再想想',
        confirmColor: '#ff0000',
        success(res) {
          if (res.confirm) {
            app.api.updateProviderInfo({
              id: that.data.providerInfo.id,
              takingStatus: (detail.value ? '1' : '0')
            }).then(res => {
              that.setData({
                'switchChecked': detail.value
              })
            })
          }
        }
      })
    }
  },
  checkProvider() {
    if (!this.data.providerInfo || !this.data.providerInfo.id) {
      // 跳转申请页面
      wx.navigateTo({
        url: "/pages/apply/index"
      })
      return false
    }
    return true
  }
})